const ctrlKeyEvents = {}
const metaKeyEvents = {}

document.onkeydown = function (e) {
  const keyCode = e.keyCode || e.which || e.charCode
  if (e.ctrlKey && ctrlKeyEvents[keyCode]) {
    ctrlKeyEvents[keyCode].forEach(fn => fn())
    e.preventDefault()
    return false
  } else if (e.metaKey && metaKeyEvents[keyCode]) {
    metaKeyEvents[keyCode].forEach(fn => fn())
    e.preventDefault()
    return false
  }
}

export function addCtrlKeyEvent (keyCode, fn) {
  ctrlKeyEvents[keyCode] = ctrlKeyEvents[keyCode] || []
  ctrlKeyEvents[keyCode].push(fn)
}

export function removeCtrlKeyEvent (keyCode, fn) {
  const events = ctrlKeyEvents[keyCode]
  if (events) {
    const index = events.indexOf(fn)
    if (index > -1) {
      events.splice(index, 1)
    }
    if (events.length <= 0) {
      delete ctrlKeyEvents[keyCode]
    }
  }
}
